package org.asiaark.developerstudio.framework.struts2;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;

/**
 * 抽象公用Action
 * 
 * @author Ivan
 * 
 */
public abstract class AbstractCommonAction extends AbstractActionSupport {

	protected final Log log = LogFactory.getLog(getClass());

	protected Map<String, String> pm = new HashMap<String, String>();


	protected Map<String, Object> rstMap = new HashMap<String, Object>();

	protected List<Object> rstList = new ArrayList<Object>();
	
	public Map<String, String> getPm() {
		return pm;
	}

	public void setPm(Map<String, String> pm) {
		this.pm = pm;
	}

	public void initParams() {
		System.out.println("this===============");
	}

	public final static String DEFAULT_RESPONSE_CHARACTER_ENCODING = "UTF-8"; // 默认编码

	private String responseCharacterEncoding;

	public void setResponseCharacterEncoding(String responseCharacterEncoding) {
		this.responseCharacterEncoding = responseCharacterEncoding;
	}

	public String getResponseCharacterEncoding() {
		if (StringUtils.isNotBlank(responseCharacterEncoding))
			return responseCharacterEncoding;
		else
			return DEFAULT_RESPONSE_CHARACTER_ENCODING;
	}

	/**
	 * 输出JSON到页面
	 * 
	 * @param json
	 * @param charset
	 * @return
	 * @throws IOException
	 */
	private String printJson(String json, String charset) throws IOException {
		HttpServletResponse response = getResponse();
		response.setContentType("application/json-rpc;charset=" + charset);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Pragma", "No-cache");
		response.setCharacterEncoding(charset);
		response.getWriter().print(json);
		return null;
	}

	/**
	 * 返回JSON结果
	 * 
	 * @param object
	 * @param charset
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	protected String jsonResult(Object object, String charset)
			throws JSONException, IOException {
		return printJson(JSONUtil.serialize(object), charset);
	}

	/**
	 * 返回JSON结果
	 * 
	 * @param object
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	protected String jsonResult(Object object) throws JSONException,
			IOException {
		return jsonResult(object, getResponseCharacterEncoding());
	}



}
